package dev.polls.skycube;

import java.io.IOException;
import java.net.URISyntaxException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.content.SharedPreferences;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class SelectGroups extends Activity
{
	GetJSon gj = new GetJSon();
	GroupActivity groupact = new GroupActivity();
	String[] groups = new String[200];
	int countgroups = 0;
	
	
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.selectgroups);
			try {
				grouplist();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
	 }
	 public void grouplist() throws ClientProtocolException, URISyntaxException, IOException, JSONException
	 {
		 SharedPreferences settings = getSharedPreferences("account_info",0);
		 String username = settings.getString("username", "");
		 String password = settings.getString("password", "");
		 
		 LinearLayout buttonlayout = (LinearLayout)findViewById(R.id.button_layout);
		 
		 JSONArray ja = gj.getGroupList(username, password);
		 int i;
		 for ( i = 0; i < ja.length(); ++i) 
		 {
			 JSONObject rec = ja.getJSONObject(i);
			 //getting json part
		     groups[i] = rec.getString("Name");
		     if(groups[i]!= null) 
		     {
		    	countgroups++;
		    	final Button b = new Button(this);
		    	b.setText(groups[i]);
		    	String id = rec.getString("Id");
		    	b.setId(Integer.parseInt(id));
		    	b.setOnClickListener(new View.OnClickListener()			 	{
			 		public void onClick(View arg0) 
			 		{
			 			
			 			System.out.println(b.getId());
			 			int id = b.getId();
			 			groupact.setGroupId(id);
			 			finish();
			 			
			 		}	 		
			 	});
		    	
		    	buttonlayout.addView(b);
		     }
		     
		 }
	 }
}
